package com.example.readbook.Sql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.readbook.Bean.BookBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Package    : com.example.readbook.Sql
 * ClassName  : SqliteUtils
 * Description: $ 数据库操作类
 * Date       : 2019/3/22 11:46
 */
public class SqliteUtils {
    private static Sqlite dbhelper;

    public static SqliteUtils getInstence(Context context) {
        if (dbhelper == null) {
            dbhelper = new Sqlite(context);
        }
        return new SqliteUtils();
    }

    /**
     * 插入数据
     * @param bookBean
     *         书籍信息
     */
    public void addBook(BookBean bookBean) {
        SQLiteDatabase writableDatabase = dbhelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", bookBean.getBookName());
        values.put("color", bookBean.getColor());
        values.put("address", bookBean.getBookAddress());
        values.put("size", bookBean.getSize());
        writableDatabase.insert("book", null, values);
        writableDatabase.close();
    }

    /**
     * 读取书籍所有信息
     * @return
     */
    public List<BookBean> readAllBook() {
        SQLiteDatabase readableDatabase = dbhelper.getReadableDatabase();
        Cursor cursor = readableDatabase.rawQuery("select*from book ", new String[]{});
        List<BookBean> lists = new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String color = cursor.getString(cursor.getColumnIndex("color"));
            String address = cursor.getString(cursor.getColumnIndex("address"));
            String size = cursor.getString(cursor.getColumnIndex("size"));
            lists.add(new BookBean(id, name, color, address, size));
        }
        cursor.close();
        readableDatabase.close();
        return lists;
    }

    /**
     * 读取书籍名字
     * @return
     */
    public List<String> readAllBookName() {
        SQLiteDatabase readableDatabase = dbhelper.getReadableDatabase();
        Cursor cursor = readableDatabase.rawQuery("select*from book ", new String[]{});
        List<String> lists = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            lists.add(name);
        }
        cursor.close();
        readableDatabase.close();
        return lists;
    }

    public void delete(String id) {
        SQLiteDatabase writableDatabase = dbhelper.getWritableDatabase();
        writableDatabase.delete("book", "id=?", new String[]{id});
        writableDatabase.close();
    }
}
